package com.vonchenchen.simple_downloader.downloader;

import android.util.Log;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;

/**
 * 下载使用的具体线程
 * Created by lidechen on 9/15/16.
 */
public class DownLoadThread implements Runnable {

    private static final String TAG = "DownLoadThread";

    private ThreadInfo mThreadInfo;

    private boolean mIsCompeleted = false;

    public void setThread(ThreadInfo threadInfo){
        mThreadInfo = threadInfo;
        //DownLoadThread.this.start();
    }

    public void resetThread(){
        mThreadInfo = null;
    }

    private void saveThreadInfo(){

    }

    @Override
    public void run() {

        BufferedInputStream bis = null;
        RandomAccessFile raf = null;

        try {

            HttpURLConnection conn = (HttpURLConnection) mThreadInfo.url.openConnection();
            conn.setInstanceFollowRedirects(false);
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            //设置当前线程下载的起点、终点
            conn.setRequestProperty("Range", "bytes=" + mThreadInfo.startPos + "-" + mThreadInfo.endPos);

            System.out.println(Thread.currentThread().getName() + "  bytes="
                    + mThreadInfo.startPos + "-" + mThreadInfo.endPos);

            int code = conn.getResponseCode();
            if(code == 200 || code == 206) {

                byte[] buffer = new byte[1024];
                bis = new BufferedInputStream(conn.getInputStream());

                raf = new RandomAccessFile(mThreadInfo.targetFile, "rwd");
                raf.seek(mThreadInfo.startPos);
                int len;
                while ((len = bis.read(buffer, 0, 1024)) != -1) {
                    raf.write(buffer, 0, len);
                    mThreadInfo.currPos += len;
                }

                mIsCompeleted = true;
                Log.d(TAG, "current thread task has finished,all size:"
                        + mThreadInfo.currPos);
            }
        }catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
